<?php
include 'Shrink.php';
include 'Library/CouchDb/Couch.php';

$couch = new Couch(array("host" => "localhost", "port" => 8888));

if(!$couch->running()) {
	die("Cannot connect to CouchDb.");
}

$db = $couch->database("bugshrink2");

if(!$db->exists()) {
	$db->create();
//	echo 'creating schema';
//	include 'createSchema.php';
}

include 'header.php';

if($id = var_register('id')) {
	//show bug
	if($bug_details = $db->get($id)) {
//		$bug_details->set('Body', $bug_details->get('Body'));
	} else {
		echo "Cannot find Bug with id: $id";
	}
} 

$edit = false;
$action = var_register('action');

switch($action) {
	case 'edit':
		$edit = true;
		//fall thru
	case 'add':
		include 'newBug.php';
		if(!empty($revision)) {
			shrink_show_bug_details($bug_details);
		}
	break;
	
	case 'delete':
		if(!$bug_details->delete()) {
			echo 'There was an Error deleting the Bug';
		}
		$id = false;
	break;
	
	case 'Open': // fall thru
		$State = 'Open';
	case 'Close':
		if(!isset($State)) { $State = 'Closed'; }
		$bug_details->set('State', $State);
		$bug_details->save();
		// fall thru
	default:
	if($id) {
		shrink_show_bug_details($bug_details);
	}
	break;
} 

if(('add' != $action) && !$id) {
	?><div id="add"><a href="?action=add">Add a Bug</a></div><hr><?php
}

if(!$id && ('add' != $action)) {
	shrink_show_bugs();
}

include 'footer.php';